package com.gk.javaservice.util.javaRequest;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.gk.javaservice.util.rest.HttpURLConnectionUtils;
import com.gk.javaservice.util.rest.RestUtil;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.*;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {
    /**
     * json 字符串
     *
     * @param url
     * @param param
     * @return
     */
    public static String getSerchPersion(String url, String param) {
        /* 1 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        /* 2 生成 GetMethod 对象并设置参数 */
        GetMethod getMethod = new GetMethod(url);
        // 设置 get 请求超时为 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理，用的是默认的重试处理：请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";

        /* 3 执行 HTTP GET 请求 */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            /* 4 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错: " + getMethod.getStatusLine());
            }
            /* 5 处理 HTTP 响应内容 */
            // HTTP响应头部信息，这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
//            for (Header h : headers) {
//                //// System.out.println(h.getName() + "------------ " + h.getValue());
//            }
            // 读取 HTTP 响应内容，这里简单打印网页内容
//            byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
//            response = new String(responseBody, param);
            //// System.out.println("----------response:" + response);
            //读取为 InputStream，在网页内容数据量大时候推荐使用
            InputStream response2 = getMethod.getResponseBodyAsStream();
            response = IOUtils.toString(response2, "utf-8");
            //// System.out.println("----------response:" +  IOUtils.toString(response2, "utf-8"));
        } catch (HttpException e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
//            // System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
//            // System.out.println("发生网络异常!");
            e.printStackTrace();
        } finally {
            /* 6 .释放连接 */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * get请求
     *
     * @param url
     * @param
     * @return
     */
    public static Object doGet(String url) {
        /* 1 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        /* 2 生成 GetMethod 对象并设置参数 */
        GetMethod getMethod = new GetMethod(url);
        // 设置 get 请求超时为 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理，用的是默认的重试处理：请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        JSONObject response = null;

        /* 3 执行 HTTP GET 请求 */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            /* 4 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错: " + getMethod.getStatusLine());
            }
            /* 5 处理 HTTP 响应内容 */
            // HTTP响应头部信息，这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
//            for (Header h : headers) {
//                //// System.out.println(h.getName() + "------------ " + h.getValue());
//            }
            // 读取 HTTP 响应内容，这里简单打印网页内容
//            byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
//            response = new String(responseBody, param);
//            // System.out.println("----------response:" + response);
            //读取为 InputStream，在网页内容数据量大时候推荐使用
            InputStream response2 = getMethod.getResponseBodyAsStream();
            String str = IOUtils.toString(response2, "utf-8");
//            // System.out.println("----------response:" +  str);
            try {
                response = JSONObject.parseObject(str);
            }catch (Exception e){
                JSONArray response1 = JSONObject.parseArray(str);
                getMethod.releaseConnection();
                return response1;
            }


        } catch (HttpException e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
//            // System.out.println("请检查输入的URL!");
//            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
//            // System.out.println("发生网络异常!");
//            e.printStackTrace();
        } finally {
            /* 6 .释放连接 */
            getMethod.releaseConnection();
        }
        return response;
    }


    /**
     * <br>
     * * 发送get请求
     * * @param url   请求URL<br>
     * * @param param 请求参数 key:value url携带参数 或者无参可不填
     * * @return<br>
     */
    public static JSONObject doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        JSONObject responsej = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                responsej = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responsej;
    }


    /**
     * 发送GET请求
     * @param url 请求URL
     * @param param 请求参数，格式为JSON对象，如无参可传null
     * @return 返回的JSON响应对象
     */
    public static JSONObject doGet(String url, JSONObject param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        JSONObject responseJson = null;
        try {
            URIBuilder builder = new URIBuilder(url);

            // 如果参数是JSONObject，则遍历并将参数添加到URI中
            if (param != null && !param.isEmpty()) {
                for (String key : param.keySet()) {
                    Object value = param.get(key);
                    if (value instanceof String) { // 确保值是字符串类型，因为URIBuilder.addParameter只接受字符串
                        builder.addParameter(key, (String) value);
                    }
                }
            }

            URI uri = builder.build();

            HttpGet httpGet = new HttpGet(uri);
            response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                responseJson = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseJson;
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        // System.out.println("doPost:");
        // System.out.println(url);
        // System.out.println(json);
//        org.apache.http.HttpHost proxy=new org.apache.http.HttpHost("192.168.10.225",8082);
//        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
//        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            StringEntity requestBody = new StringEntity( jsonStr, "utf-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;");//发送json数据需要设置contentType
//            s.setContentType("application/text;");//发送json数据需要设置contentType
//            // System.out.println("StringEntity:"+s);
            post.setEntity(s);
//            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(120000)
//                    .setSocketTimeout(120000).setConnectTimeout(120000).build();
//            post.setConfig(requestConfig);
            HttpResponse res = client.execute(post);
//            // System.out.println(res.getStatusLine().getStatusCode());
//            // System.out.println(EntityUtils.toString(res.getEntity()));
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);// 返回json格式：
//                // System.out.println("result:"+result);
//                response = JSONObject.fromObject(result);
                response = JSONObject.parseObject(result);
            }
            /* 6 .释放连接 */
            client.close();
        } catch (Exception e) {
//            throw new RuntimeException(e);
//            e.printStackTrace();
        }
//        finally {
//            /* 6 .释放连接 */
//            client.close();
//        }

        return response;
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPostTimeOut(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        // System.out.println("doPost:");
        // System.out.println(url);
        // System.out.println(json);
//        org.apache.http.HttpHost proxy=new org.apache.http.HttpHost("192.168.10.225",8082);
//        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
//        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            StringEntity requestBody = new StringEntity( jsonStr, "utf-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;");//发送json数据需要设置contentType
//            s.setContentType("application/text;");//发送json数据需要设置contentType
//            // System.out.println("StringEntity:"+s);
            post.setEntity(s);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(2000)
                    .setSocketTimeout(2000).setConnectTimeout(2000).build();
            post.setConfig(requestConfig);
            HttpResponse res = client.execute(post);
//            // System.out.println(res.getStatusLine().getStatusCode());
//            // System.out.println(EntityUtils.toString(res.getEntity()));
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);// 返回json格式：
//                // System.out.println("result:"+result);
//                response = JSONObject.fromObject(result);
                response = JSONObject.parseObject(result);
            }
            /* 6 .释放连接 */
            client.close();
        } catch (Exception e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
//        finally {
//            /* 6 .释放连接 */
//            client.close();
//        }

        return response;
    }




    public static JSONObject doPostForNode(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();

//        org.apache.http.HttpHost proxy=new org.apache.http.HttpHost("192.168.10.225",8082);
//        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
//        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            StringEntity requestBody = new StringEntity( jsonStr, "utf-8");
//            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;");//发送json数据需要设置contentType
            // System.out.println("StringEntity:" + s);
            post.setEntity(s);
            HttpResponse res = client.execute(post);

            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
//                response = JSONObject.fromObject(result);
                response = JSONObject.parseObject(result);
            }
            /* 6 .释放连接 */
            client.close();
        } catch (Exception e) {
//            throw new RuntimeException(e);
        }
//        finally {
//            /* 6 .释放连接 */
//            client.close();
//        }

        return response;
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost2(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();

//        org.apache.http.HttpHost proxy=new org.apache.http.HttpHost("192.168.10.225",8082);
//        RequestConfig requestConfig=RequestConfig.custom().setProxy(proxy).build();
//        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            // System.out.println("json.toString():" + json.toString());
            StringEntity s = new StringEntity(json.toString());
//            s.setContentEncoding("UTF-8");
            // System.out.println("StringEntity:" + s);
            s.setContentEncoding("UTF-8");


//            s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
            s.setContentType("text/json;charset=UTF-8");//发送json数据需要设置contentType
            // System.out.println("StringEntity:" + s);
            // System.out.println(s);
            post.setEntity(s);
//            post.setH
            // System.out.println(post);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
//                response = JSONObject.fromObject(result);
                response = JSONObject.parseObject(result);
            }
            /* 6 .释放连接 */
            client.close();
        } catch (Exception e) {
//            throw new RuntimeException(e);
        }
//        finally {
//            /* 6 .释放连接 */
//            client.close();
//        }

        return response;
    }

    public static String sendHttpPost(String url, JSONObject json, HashMap<String, String> headers) {
        String jsonStr = json.toString();
        HttpPost post = new HttpPost(url);
        String response = "";
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setConnectTimeout(10000).setSocketTimeout(10000).build();
        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom().setDefaultRequestConfig(config)
                    .setSslcontext(SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build())
                    .setMaxConnTotal(500)
                    .setMaxConnPerRoute(200).build();
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
            StringEntity requestBody = new StringEntity(jsonStr, "utf-8");
            post.setEntity(requestBody);
            CloseableHttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            inStream.close();
            response = strber.toString();
        } catch (Exception e) {
//            logger.info(e.getStackTrace());
        } finally {
            try {
                client.close();
            } catch (Exception e) {
//                logger.info(e.getStackTrace());
            }
        }
        return response;
    }


    public static JSONObject hasDirectory(String url, HashMap json){
        try {
            RestUtil restUtil = new RestUtil();

            // String resultString = restUtil.load("http://"+ip+":9092/File/hasDirectory","path="+path);

//           HashMap map = new HashMap();
//           params.put("path",path);
//
//           HashMap<String, Object> map = new HashMap<>();
//           map.put("op", sdVoEBean.getOp());
//           map.put("source_device", sdVoEBean.getSource_device());
//           map.put("stream_type", sdVoEBean.getStream_type());
//           map.put("stream_index", sdVoEBean.getStream_index());
//           map.put("subscription_index", sdVoEBean.getSubscription_index());
            String resultString= HttpURLConnectionUtils.postForm(url,null,json);
            // System.out.println(resultString);
            JSONObject jsonObject = JSONObject.parseObject(resultString);

            String data=jsonObject.getString("data");
            // System.out.println(data);
//       JSONArray json = JSONArray.fromObject(data );
            return null;
        } catch (Exception e) {

            // TODO: handle exception

            // System.out.print(e.getMessage());
            return null;
        }
    }

    public static JSONObject sendPost(String url,String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        JSONObject response = null;
        byte[] bytes = new byte[0];
        String utf8String=null;
        try {
            bytes = param.getBytes("UTF-8");
            utf8String = new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {


            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("Content-Type", "0");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
//            out.print(param);

            out.print(utf8String);

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            // System.out.println("result:::" + result);
            response = JSONObject.parseObject(result);
        } catch (Exception e) {
            System.err.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return response;
    }

    public static JSONObject sendPostCHN(String url, String param) {
//        // System.out.println("sendPostCHN param:");
//        // System.out.println(param);
        HttpURLConnection httpConn = null;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        JSONObject response = null;

        try {
            URL realUrl = new URL(url);

            // 打开和URL之间的连接并转换为HttpURLConnection以便设置POST方法等HTTP特定属性
            httpConn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用请求属性
            httpConn.setRequestProperty("accept", "*/*");
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 发送POST请求必须设置的方法和输入输出流开启标志
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("POST");

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(), StandardCharsets.UTF_8));
            // 发送请求参数
            out.print(param);

            // flush输出流的缓冲区
            out.flush();

            // 定义BufferedReader输入流来读取URL的响应
            try {
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
            } catch (IOException e) {
                if (httpConn != null) {
                    int responseCode = httpConn.getResponseCode();
                    System.err.println("获取服务器响应输入流时发生异常：" + e.getMessage());
                    System.err.println("服务器返回的状态码: " + responseCode);
                }
                e.printStackTrace();
            }

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            // System.out.println("result:::" + result);
            try {
                response = JSONObject.parseObject(result);
            } catch (JSONException je) {
                System.err.println("JSON解析异常：" + je.getMessage());
                je.printStackTrace();
            }

        } catch (Exception e) {
            System.err.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (httpConn != null) {
                    httpConn.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }
    //调用
    public static void main(String arg[]) throws Exception {

//
////        //String url = "http://192.168.10.226:809/system";
//        String url = "http://192.168.10.226:809/patient";
//        JSONObject params = new JSONObject();
//        params.put("personName", "name");
//        params.put("personCode", "230882xxxxxx2116");
//        JSONObject param2 = new JSONObject();
//        param2.put("pageNo", 1);
//        param2.put("pageSize", 20);
//        params.put("page", param2);
//        String param = "q=" + params.toString();
//        //get 请求
//        String ret = getSerchPersion(url, "");
//        // System.out.println("ret:::" + ret);
//
//        //先将字符串转成单个对象
//        JSONObject jsonObject = JSONObject.parseObject(ret);
//        //抽出对象中的对象集合字符串
//        String data = jsonObject.getString("data");
//        // System.out.println("data:::" + data);
//
////        JSONObject jsonObject2 = JSONObject.parseObject(data);
////        //抽出对象中的对象集合字符串
////        String signalList = jsonObject2.getString("signalList");
////        // System.out.println("signalList:::"+signalList);
//
//        //String转jsonArray
//
//        JSONArray jsArr = JSONObject.parseArray(data);
//        List<PatinentCase> list = JSONObject.parseArray(jsArr.toJSONString(), PatinentCase.class);
//        for (PatinentCase s : list
//        ) {
//            // System.out.println("s:::" + s);
//        }


        //        将post请求参数写到map中（map中可以存map）
        HashMap<String, Object> dataList = new HashMap<>();
        dataList.put("index", "7");
        dataList.put("model_index", "7");
        dataList.put("screen_index", "");
        dataList.put("interface", "");
//        dataList.put("screen_index","3");
//        dataList.put("interface","SDI-1");
        HashMap<String, Object> data = new HashMap<>();
        data.put("info", "modeChange");
        data.put("status", "0");
        data.put("dataList", dataList);

        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "2");
        map.put("status", "0");
        map.put("data", data);


//        将map转为json对象
        JSONObject json = new JSONObject(map);
        String url = "http://192.168.10.226:809/web/system";
        JSONObject reg = doPost(url, json);
        // System.out.println("reg:" + reg.getString("message"));
    }

    public static JSONObject sendPostWithJson(String url, JSONObject json) {
        // 返回的结果
        String jsonResult = "";
        try {
            HttpClient client = new HttpClient();
            // 连接超时
            client.getHttpConnectionManager().getParams().setConnectionTimeout(3 * 1000);
            // 读取数据超时
            client.getHttpConnectionManager().getParams().setSoTimeout(3 * 60 * 1000);
            client.getParams().setContentCharset("UTF-8");
            PostMethod postMethod = new PostMethod(url);

            postMethod.setRequestHeader("content-type", "application/json");


            StringRequestEntity requestEntity = new StringRequestEntity(json.toString(), "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);

            int status = client.executeMethod(postMethod);
            // System.out.println("url:" + url);
            // System.out.println("status:" + status);
            if (status == HttpStatus.SC_OK) {
                jsonResult = postMethod.getResponseBodyAsString();
            } else {
                throw new RuntimeException("接口连接失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("接口连接失败！");
        }
        // System.out.println("+++++++++++++++++++");
        // System.out.println(jsonResult);
        // System.out.println("+++++++++++++++++++");
        return JSONObject.parseObject(jsonResult);
    }

}
